import axios from 'axios';
import { getAppSite } from '@/common/js/service-common';

import { decrypt as AESDecrypt, encrypt as AESEncrypt } from 'crypto-js/aes';
import { parse } from 'crypto-js/enc-utf8';
import { nameConfig } from '@theme/vm';

/**
 * 判断是否是安卓系统
 */
export function isAndroid(): boolean {
  try {
    return /(android|adr|xiaomi)/gi.test(navigator.userAgent);
  } catch (error) {
    uploadErrorInfo('commonjs.isAndroid', error, false);
    return false;
  }
}

/**
 * 判断是否是ios系统
 */
export function isIOS(): boolean {
  try {
    const userAgent: string = navigator.userAgent;

    return (
      /\(i[^;]+;( U;)? CPU.+Mac OS X/gi.test(userAgent) &&
      !/xiaomi/gi.test(userAgent)
    );
  } catch (error) {
    uploadErrorInfo('commonjs.isIOS', error, false);
    return false;
  }
}

/**
 * 浏览器类型
 */
export enum BROWSER {
  /**
   * QQ浏览器
   */
  QQ = 'QQBROWSER',
  /**
   * UC浏览器
   */
  UC = 'UCBROWSER',
  /**
   * IE浏览器
   */
  IE = 'MSIE',
  /**
   * Firefox浏览器
   */
  FIREFOX = 'FIREFOX',
  /**
   * Chrome浏览器
   */
  CHROME = 'CHROME',
  /**
   * Opera浏览器
   */
  OPERA = 'OPERA',
  /**
   * Safari浏览器
   */
  SAFARI = 'SAFARI',
  /**
   * 搜狗浏览器
   */
  SOGOU = 'SOGOU',
  /**
   * 百度浏览器
   */
  BAIDU = 'BAIDU',
}

/**
 * 获取浏览器类型
 */
export function getBrowserType(): string {
  try {
    const result = navigator.userAgent.match(
      /(QQBROWSER|UCBROWSER|MSIE|FIREFOX|CHROME|OPERA|SAFARI|SOGOU|BAIDU)/gi
    );
    return result ? result[0].toLocaleUpperCase() : 'UNKNOWN';
  } catch (error) {
    uploadErrorInfo('commonjs.getBrowserType', error, false);
    return 'UNKNOWN';
  }
}

/**
 * 判断是否在ios从百度App打开
 */
export function isIOSBaiduWebview(): boolean {
  try {
    return isIOS() && /baiduboxapp/gi.test(navigator.userAgent);
  } catch (error) {
    uploadErrorInfo('commonjs.isIOSBaiduWebview', error, false);
    return false;
  }
}

/**
 * 判断是否是微信
 */
export function isWechat(): boolean {
  try {
    return /micromessenger/gi.test(navigator.userAgent);
  } catch (error) {
    uploadErrorInfo('commonjs.isWechat', error, false);
    return false;
  }
}

/**
 * 根据参数名获取地址栏参数
 * @param {string} name 参数名
 */
export function getQueryParamByName(name): string {
  try {
    const regexp = new RegExp('(^|&)' + name + '=([^&]*)(&|$)');
    const result = window.location.search.substr(1).match(regexp);
    return result ? unescape(result[2]) : '';
  } catch (error) {
    uploadErrorInfo('commonjs.getQueryParamByName', error, false);
    return '';
  }
}

/**
 * 生成全部唯一标识符（UUID）
 */
export function createUUID(): string {
  try {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(
      /[xy]/g,
      function (char) {
        const rendomNumer = (Math.random() * 16) | 0;
        const result = char === 'x' ? rendomNumer : (rendomNumer & 0x3) | 0x8;

        return result.toString(16);
      }
    );
  } catch (error) {
    uploadErrorInfo('commonjs.createUUID', error, false);
    return '';
  }
}

/**
 * 获取地址栏参数
 */
export function getQueryParams(): object {
  try {
    const search = decodeURI(location.search);
    const result = {};
    // 判断是否存在请求的参数
    if (search) {
      const params = search.substr(1).split('&');
      // 截取所有请求的参数，以数组方式保存
      params.forEach(function (param) {
        const keyValue = param.split('=');
        // 获取该参数名称，值。其中值以unescape()方法解码，有些参数会加密
        result[unescape(keyValue[0])] = unescape(keyValue[1]);
      });
    }
    // 返回改参数列表对象
    return result;
  } catch (error) {
    uploadErrorInfo('commonjs.getQueryParams', error, false);
    return {};
  }
}

/**
 * 补零 个位数前面补零
 *
 * @param {*} val 值
 * @returns {string} 补零后的值
 */
function fillZero(val): string {
  try {
    return val < 10 ? '0' + val : '' + val;
  } catch (error) {
    uploadErrorInfo('commonjs.fillZero', error, false);
    return val;
  }
}

/**
 * 日期格式化 YYYY-MM-DD HH:mm:ss
 *
 * @param {Date} date 日期对象
 * @returns {string} 格式化后的值
 */
function formatDate(date: Date): string {
  try {
    const year = date.getFullYear();
    const month = fillZero(date.getMonth() + 1);
    const day = fillZero(date.getDate());
    const hours = fillZero(date.getHours());
    const minutes = fillZero(date.getMinutes());
    const seconds = fillZero(date.getSeconds());

    return (
      year +
      '-' +
      month +
      '-' +
      day +
      ' ' +
      hours +
      ':' +
      minutes +
      ':' +
      seconds
    );
  } catch (error) {
    uploadErrorInfo('commonjs.formatDate', error, false);
    return '';
  }
}

/**
 * 数据上报请求
 * @param {string} action
 * @param {string} app
 */
export function reportInfo(action, app): void {
  // try {
  //   const date = new Date();
  //   const buryPoint = {
  //     action,
  //     app,
  //     ip: window.returnCitySN ? window.returnCitySN.cip : '', // 从引入进来的ip js库获取ip
  //     i_code: getQueryParamByName('i_code'),
  //     r_code: getQueryParamByName('r_code'),
  //     os: isAndroid() ? 'android' : 'ios',
  //     client_type: 'h5',
  //     user_agent: navigator.userAgent,
  //     url: location.href,
  //     error_info: '',
  //     http_code: '200',
  //     download_time: formatDate(date)
  //   };
  //   const report_url =
  //     process.env.DIY === 'prod' ? '//report.ul68qh.com' : '//test.ul68qh.com';
  //   axios({
  //     url: report_url + '/downloadlogs',
  //     method: 'post',
  //     headers: { 'Content-Type': 'application/json' },
  //     data: {
  //       records: [
  //         {
  //           value: buryPoint
  //         }
  //       ]
  //     }
  //   }).catch(function(error) {
  //     // uploadErrorInfo('commonjs.axios.downloadlogs', error, false);
  //   });
  // } catch (error) {
  //   uploadErrorInfo('commonjs.reportInfo', error, false);
  // }
}

/**
 * v3.0下载页数据上报请求
 * @param {string} action
 */
export function reportInfoV3(action): void {
  // try {
  //   // 秘钥
  //   const key = '123456';
  //   const date = new Date();
  //   const time = date.getTime();
  //   const data = {
  //     uuid: getCacheUUID(),
  //     ip: window.returnCitySN ? window.returnCitySN.cip : '', // 从引入进来的ip js库获取ip
  //     i_code: getQueryParamByName('i_code'),
  //     r_code: getQueryParamByName('r_code'),
  //     os: isAndroid() ? 'android' : 'ios',
  //     client_type: 'h5',
  //     view_time: formatDate(date),
  //     user_agent: navigator.userAgent,
  //     ios_sports_pv: 0,
  //     ios_yabo_pv: 0,
  //     ios_sports_uv: 0,
  //     ios_yabo_uv: 0,
  //     ios_yabo_download_click: 0,
  //     ios_sports_download_click: 0,
  //     ios_sports_download_c_pv: 0,
  //     ios_yabo_download_c_pv: 0,
  //     ios_sports_trust_click: 0,
  //     ios_yabo_trust_click: 0,
  //     ios_sports_trust_uv: 0,
  //     ios_yabo_trust_uv: 0,
  //     android_sports_download_pv: 0,
  //     android_sports_download_uv: 0,
  //     android_sports_download_click: 0,
  //     android_yabo_download_pv: 0,
  //     android_yabo_download_uv: 0,
  //     android_yabo_download_click: 0
  //   };
  //   data[action] = 1;
  //   const body = JSON.stringify(data);
  //   const report_url =
  //     process.env.DIY === 'prod'
  //       ? '//logs.go.uploadlog.com:443/pvuv'
  //       : '//logs.go.uploadlog.com:81/pvuv';
  //   axios({
  //     url: report_url,
  //     method: 'post',
  //     data: qs.stringify({
  //       body,
  //       h2: md5(key + body + time),
  //       h1: time
  //     })
  //   }).catch(function(error) {
  //     uploadErrorInfo('commonjs.axios.pvuv', error, false);
  //   });
  // } catch (error) {
  //   uploadErrorInfo('commonjs.reportInfoV3', error, false);
  // }
}

/**
 * 获取缓存中的ID，不存在就创建新的
 */
export function getCacheUUID(): string {
  try {
    let uuid = localStorage.getItem('uuid');

    if (!uuid) {
      uuid = createUUID();
      localStorage.setItem('uuid', uuid);
    }

    return uuid;
  } catch (error) {
    uploadErrorInfo('commonjs.getCacheUUID', error, false);
    return createUUID();
  }
}

/**
 * 是否微信，qq，微博的webview
 */
export function isTencentWebview(): boolean {
  try {
    const ua = navigator.userAgent.toLowerCase();
    const isWeibo = /weibo/i.test(ua);
    const isQQ = / QQ/i.test(ua);
    let allowedAgent = isWechat() || isWeibo || isQQ;

    return allowedAgent ? true : false;
  } catch (error) {
    uploadErrorInfo('commonjs.isTencentWebview', error, false);
    return false;
  }
}

export function isQQ(): boolean {
  let isBrowser = navigator.userAgent.match(/MQQBrowser/);
  return isBrowser ? true : false;
}

/**
 * 上报错误堆栈的信息
 *
 * @export
 * @param {string} info 错误信息
 * @param {*} error 错误对象
 * @param {boolean} isGlobal 是否全局错误
 */
export function uploadErrorInfo(
  info: string,
  error: any,
  isGlobal: boolean
): void {
  const errorStack = error && error.stack ? error.stack : '';
  reportInfo(
    isGlobal ? 'global_error' : 'code_error',
    info + ' -> ' + errorStack
  );
}

/**
 * 捕获全局异常
 */
export function catchGlobalError(): void {
  window.onerror = function (message, source, lineno, colno, error) {
    uploadErrorInfo('window.onerror', error, true);
    return true;
  };

  window.addEventListener('unhandledrejection', function (error) {
    uploadErrorInfo('unhandledrejection', error, true);
  });
}

/**
 * 使用complete的图片属性检测图片是否加载完成
 *
 * @static
 * @param {Array} imgList
 * @memberof DomUtil
 */
export function onloadImage(imgList): void {
  // const safeDom = document.querySelector<HTMLElement>('#safeDown');
  // if (isAndroid()) {
  //   safeDom.style.display = 'block';
  // }
  // try {
  //   let i = 0;
  //   let timer;
  //   const len = imgList.length;
  //   const load = function (src: { imgurl: string }) {
  //     if (i < len) {
  //       const img_obj = new Image();
  //       img_obj.src = src.imgurl;
  //       timer = setInterval(function () {
  //         if (img_obj.complete) {
  //           clearInterval(timer);
  //           load(imgList[i++]);
  //         }
  //       }, 80);
  //     } else {
  //       // 完成
  //       const installBtn = document.querySelector<HTMLElement>('#install');
  //       if (installBtn) {
  //         installBtn.innerText = '立即下载';
  //         installBtn.removeAttribute('disabled');
  //         DomUtil.addClass(installBtn, 'can_install_class');
  //       }
  //     }
  //   };
  //   setTimeout(function () {
  //     load(imgList[i]);
  //   }, 500);
  // } catch (error) {
  //   uploadErrorInfo('commonjs.onloadImage', error, false);
  // }
  const installBtn = document.querySelector<HTMLElement>('#install');
  if (installBtn) {
    installBtn.innerText = nameConfig.downText;
    installBtn.removeAttribute('disabled');
    DomUtil.addClass(installBtn, 'can_install_class');
  }
  // webClip 相关
  const fdqInstallBtn = document.querySelector<HTMLElement>('#fdqInstall');
  if (isNeedWebClip() && isIOS()) {
    if (fdqInstallBtn) {
      fdqInstallBtn.innerText = '防掉签下载';
      fdqInstallBtn.removeAttribute('disabled');
      DomUtil.addClass(fdqInstallBtn, 'can_install_class');
    }
  } else {
    if (fdqInstallBtn) {
      fdqInstallBtn.style.display = 'none';
    }
  }
}
// webClip 相关
export const isNeedWebClip = (needShow: boolean = false) => {
  const needWebClip = ['ddh'];
  return needWebClip.find((brandName) => brandName === nameConfig.brand);
};

// webClip 相关
export const isNeedKeFuWebClip = () => {
  return nameConfig.isWebClip;
};

/**
 * Dom工具库
 *
 * @export Dom工具库
 * @class DomUtil
 */
export class DomUtil {
  /**
   * 隐藏元素
   *
   * @static
   * @param {HTMLElement} node
   * @memberof DomUtil
   */
  public static hide(node: HTMLElement): void {
    try {
      node.style.display = 'none';
    } catch (error) {
      uploadErrorInfo('commonjs.DomUtil.hide', error, false);
    }
  }

  /**
   * 展示元素
   *
   * @static
   * @param {HTMLElement} node
   * @memberof DomUtil
   */
  public static show(node: HTMLElement): void {
    try {
      node.style.display = 'block';
    } catch (error) {
      uploadErrorInfo('commonjs.DomUtil.show', error, false);
    }
  }

  /**
   * 追加子元素至父元素
   *
   * @static
   * @template T
   * @param {T} container 父元素
   * @param {string} content 子元素
   * @memberof DomUtil
   */
  public static append<T extends Element>(container: T, content: string): void {
    try {
      const div = document.createElement('div');
      div.innerHTML = content;
      const node = div.firstChild;
      if (node) {
        container.appendChild(node);
      }
    } catch (error) {
      uploadErrorInfo('commonjs.DomUtil.append', error, false);
    }
  }

  /**
   * 移除当前元素
   *
   * @static
   * @param {Node} node
   * @memberof DomUtil
   */
  public static remove(node: Node): void {
    try {
      const pNode = node.parentNode;

      if (pNode) {
        pNode.removeChild(node);
      }
    } catch (error) {
      uploadErrorInfo('commonjs.DomUtil.remove', error, false);
    }
  }

  /**
   * 创建元素
   *
   * @static
   * @template T
   * @param {string} template 元素模板 domstring
   * @returns {(T | null)}
   * @memberof DomUtil
   */
  public static create<T extends Element>(template: string): T | null {
    try {
      let result: T | null = null;

      try {
        const div = document.createElement('div');
        div.innerHTML = template;
        result = div.firstChild as T | null;
      } catch (error) {
        result = null;
      }

      return result;
    } catch (error) {
      uploadErrorInfo('commonjs.DomUtil.create', error, false);
      return null;
    }
  }

  /**
   * 切换class
   *
   * @static
   * @param {HTMLElement} node
   * @param {string} className
   * @memberof DomUtil
   */
  public static toggleClass(node: HTMLElement, className: string): void {
    try {
      node.classList.toggle(className);
    } catch (error) {
      uploadErrorInfo('commonjs.DomUtil.toggleClass', error, false);
    }
  }

  /**
   * 新增class
   *
   * @static
   * @param {HTMLElement} node
   * @param {string} className
   * @memberof DomUtil
   */
  public static addClass(node: HTMLElement, className: string): void {
    try {
      node.classList.add(className);
    } catch (error) {
      uploadErrorInfo('commonjs.DomUtil.addClass', error, false);
    }
  }
}

/**
 * 获取cookie
 *
 * @export
 * @param {string} name
 * @returns any
 */
export function getCookie(name): string | null {
  let arr: any;
  const reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)');
  if ((arr = document.cookie.match(reg))) {
    return unescape(arr[2]);
  } else {
    return null;
  }
}

/**
 * 获取i_code邀请码
 *
 * @export
 * @returns
 */
export function getICode(): string {
  // 先从url取，再从localstorage取，最后从cookie取
  const icode_url = location.search ? getQueryParamByName('i_code') : '';
  let icode_local;
  try {
    icode_local = localStorage.getItem('i_code');
  } catch (error) {
    console.log(error);
    icode_local = '';
  }
  const icode_cookie = getCookie('i_code');

  return icode_url || icode_local || icode_cookie || '';
}

/**
 * 获取r_code邀请码
 *
 * @export
 * @returns
 */
export function getRCode(): string {
  // 先从url取，再从localstorage取，最后从cookie取
  const icode_url = location.search ? getQueryParamByName('r_code') : '';
  let icode_local;
  try {
    icode_local = localStorage.getItem('r_code');
  } catch (error) {
    console.log(error);
    icode_local = '';
  }
  const icode_cookie = getCookie('r_code');

  return icode_url || icode_local || icode_cookie || '';
}

export function getServerTimeDiff(): number {
  try {
    const localStorageItem = localStorage.getItem('server_time');
    if (!localStorageItem) {
      return 0;
    }
    const serverTime = JSON.parse(localStorageItem || '');
    return serverTime ? (serverTime.diff as number) : 0;
  } catch (error) {
    console.log(error);
    return 0;
  }
}

/**
 * 生成设备号
 */
function generateDeviceNum() {
  let uuid = localStorage.getItem('uuid');
  // localStorage没有uuid就重新生成
  if (!uuid) {
    const { userAgent } = window.navigator;
    let systemType = '';
    if (userAgent.indexOf('Windows') !== -1) {
      systemType = 'windows';
    }
    if (userAgent.indexOf('Mac') !== -1) {
      systemType = 'mac';
    }
    if (userAgent.indexOf('Linux') !== -1) {
      systemType = 'linux';
    }
    uuid = `web-${systemType}-${Math.random()
      .toString(36)
      .substr(2)}-${Math.random().toString(36).substr(2)}`;
    localStorage.setItem('uuid', uuid);
  }
  return uuid;
}

// 请求header
export const commonHeaders = (clientType: string = 'web') => ({
  // 客户端类型，如果是APP，则使用app的设备类型
  SKKTW: clientType,
  FUQVA: 'v1.0.1',
  DSRVY: getAppSite({}).data,
  RWNAV: sessionStorage.getItem('tb-token') || getCookie('tb-token') || '',
  NLGFN: generateDeviceNum(),
  'X-KK-APPKEY': 'qIrNyMVj4T',
  'Content-Type': 'application/json',
});

export const encryptToHT = (text: string, { key, iv }: any = {}): string => {
  return AESEncrypt(text, parse(key), {
    iv: parse(iv),
    // mode: CryptoJS.mode.CBC, // 默认就是CBC
    // padding: CryptoJS.pad.Pkcs7, // 默认就是pkcs7
  }).ciphertext.toString();
};

// 文件下载
export const fileUrlHandled = (url: string, fileName?: string) => {
  const fileUrl = url;
  const a = document.createElement('a');
  a.style.display = 'none';
  a.href = fileUrl;
  a.target = '_blank';
  if (fileName) {
    a.download = fileName;
  }
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
};

export const ModalType = {
  iosNoSafari: 'iosNoSafari',
  ios: 'ios',
  android: 'android',
};

// 这里处理title中英文混合Base64会出错问题
export const getEnTitleName = (brandId: any) => {
  if (brandId === 'pgdz') {
    return 'PG';
  } else {
    return '';
  }
};

// 如果url携带参数 isAppUpdate 则弹框提示
export const isAppUpdate = () => {
  return getQueryParamByName('isAppUpdate');
};

// 在url后面添加 isAppUpdate 参数
export const addAppUpdateParam = (url: string) => {
  const param = getQueryParamByName('isAppUpdate') || '1';
  return url + (url.includes('?') ? '&' : '?') + 'isAppUpdate=' + param;
};

// 在url 后面添加参数
export const urlAddParam = (url: string, params: string) => {
  if (!params) return url;

  if (url.indexOf('?') >= 0) {
    return url + '&' + params;
  } else {
    return url + '?' + params;
  }
};
